package com.quartz.controller;

import com.quartz.bean.SysTask;
import com.quartz.result.JsonResult;
import com.quartz.service.IJobManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * @Description 任务管理控制，此处只实现了增加和删除，
 * @Author LCXU
 * @Date 2020/12/28 14:01
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/task")
public class SysTaskController {

    @Autowired
    private IJobManageService jobManageService;

    private boolean validateParmas(SysTask task) {
        return task != null && StringUtils.isNotBlank(task.getCron())
                && StringUtils.isNotBlank(task.getJobGroup())
                && StringUtils.isNotBlank(task.getJobName());
    }

    @GetMapping("/add")
    public JsonResult addTask() {
        return JsonResult.success();
    }

    /**
     * @Author LCXU
     * @Description //添加一个任务
     * @Date 10:20 2021/1/15
     * @Param [task]
     * @return com.quartz.result.JsonResult
     */
    @PostMapping("/add-task")
    public JsonResult addTask(@RequestBody SysTask task) {
        if (validateParmas(task)) {
            try {
                this.jobManageService.addJob(task);
                return JsonResult.success();
            } catch (Exception e) {
                log.error("添加任务异常，异常任务名称：" + task.getJobGroup() + "; 任务名称" + task.getJobName());
            }
        }
        return JsonResult.error();
    }

    /**
     * @Author LCXU
     * @Description //删除一个任务
     * @Date 10:20 2021/1/15
     * @Param [task]
     * @return com.quartz.result.JsonResult
     */
    @RequestMapping("/delete-task")
    public JsonResult deleteTask(@RequestBody SysTask task) {
        if (validateParmas(task)) {
            try {
                this.jobManageService.deleteJob(task);

                return JsonResult.success();
            } catch (Exception e) {
                log.error("删除任务异常，异常任务名称：" + task.getJobGroup() + "; 任务名称" + task.getJobName());
            }
        }
        return JsonResult.error();
    }
}
